package com.wushi.lenovo.asia5b.app_ui.h5;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.widget.ContentLoadingProgressBar;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.mvp.base.BaseMvpActivity;
import com.mvp.base.model.ResultModel;
import com.mvp.utils.ToastUtil;
import com.wushi.lenovo.asia5b.R;
import com.wushi.lenovo.asia5b.app_config.CommonConstant;
import com.wushi.lenovo.asia5b.app_config.UserRepository;
import com.wushi.lenovo.asia5b.app_di.APPComponentFactory;
import com.wushi.lenovo.asia5b.app_di.other.mvpview.H5ActivityView;
import com.wushi.lenovo.asia5b.app_di.other.presenter.H5ActivityPresenter;
import com.wushi.lenovo.asia5b.app_event.LoginEvent;
import com.wushi.lenovo.asia5b.app_event.UpdateWisnStateEvent;
import com.wushi.lenovo.asia5b.app_model.good.AddCartModel;
import com.wushi.lenovo.asia5b.app_model.good.ThirdContentModel;
import com.wushi.lenovo.asia5b.app_model.h5.H5Bean;
import com.wushi.lenovo.asia5b.app_model.h5.H5GoodsDetailBean;
import com.wushi.lenovo.asia5b.app_model.h5.H5WishBean;
import com.wushi.lenovo.asia5b.app_model.h5.JsCall;
import com.wushi.lenovo.asia5b.app_utils.helper.H5Hepler;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import okhttp3.ResponseBody;

import static java.lang.String.format;
import static timber.log.Timber.d;

/**
 * Created by zhangyuncai on 2019/4/13.
 */
public abstract class H5Activity extends BaseMvpActivity<H5ActivityView, H5ActivityPresenter> implements H5ActivityView {

    protected static final String H5_URL = "url";
    protected static final String H5_TITLE = "title";
    public static final String H5_JSCALL_NAME = "Android";

    protected JsCall jsCall;
    protected H5GoodsDetailBean h5GoodsDetailBean;//商品列表跳转其他界面留一个该商品的标记

    //以下全局变量要加
    private ValueCallback<Uri> mUploadMessage;
    public ValueCallback<Uri[]> uploadMessage;
    public static final int REQUEST_SELECT_FILE = 100;
    private final static int FILECHOOSER_RESULTCODE = 2;
    private boolean isShowloading = false;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_h5;
    }

    @Override
    protected void constructComponent() {
        APPComponentFactory.getAppBaseComponent().inject(this);
    }

    protected abstract WebView getWebView();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        initH5View();
    }

    //优化一些基类字段信息
    protected void initH5View() {
        jsCall = new JsCall() {
            @Override
            public void callbackParam(String param) {
                H5Bean h5Bean = H5Hepler.parseUrl(mActivity, param);
                if (h5Bean != null) {
                    if (h5Bean instanceof H5GoodsDetailBean) {
                        H5GoodsDetailBean h5GoodsDetailBean = (H5GoodsDetailBean) h5Bean;
                        H5Activity.this.h5GoodsDetailBean = h5GoodsDetailBean;
                        if (TextUtils.equals("openPicGoodsUrl", h5GoodsDetailBean.getDoX())) {
                            getPresenter().getProductIdByUrl(h5GoodsDetailBean.getGoods_url());
                        }
                    } else if (h5Bean instanceof H5WishBean) {
                        H5WishBean h5WishBean = (H5WishBean) h5Bean;
                        d("--->>>>>>>>---开始添加收藏:" + h5WishBean.getGoods_id());
                        if (UserRepository.isLogin(mActivity)) {
                            getPresenter().changeWishType(h5WishBean);
                        }
                    }
                }
                //通知下级页面
                callBackByJs(h5Bean);
            }
        };
    }

    protected void callBackByJs(H5Bean h5Bean) {

    }

    protected void changeWishType(WebView webView, H5WishBean h5WishBean) {
        String js = "";
        if (TextUtils.equals(h5WishBean.getProduct_wishlist(), "1")) {//当前状态已收藏,那么就删除收藏
            js = String.format(CommonConstant.WISHNORMAL2, h5WishBean.get_index(), h5WishBean.getGoods_id());
        } else {//当前状态未收藏,那么就添加收藏
            js = String.format(CommonConstant.WISHPRESS2, h5WishBean.get_index(), h5WishBean.getGoods_id());
        }
        d("--->>>>>>>>---执行js代码:" + js);
        webView.evaluateJavascript(js, null);
    }

    /**
     * @param webView
     * @param index   商品列表的角标值
     * @param isWish  设置收藏后的状态
     */
    protected void changeWishType(WebView webView, String index, String goods_id, boolean isWish) {
        String js = "";
        if (!isWish) {//设置状态未非收藏
            js = String.format(CommonConstant.WISHNORMAL2, index, goods_id);
        } else {//当前状态未收藏,那么就添加收藏
            js = String.format(CommonConstant.WISHPRESS2, index, goods_id);
        }
        d("--->>>>>>>>---执行js代码:" + js);
        webView.evaluateJavascript(js, null);
    }

    @RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
    protected WebSettings setting(WebView webView) {
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);//是否允许执行js，默认为false。设置true时，会提醒可能造成XSS漏洞
        settings.setAllowContentAccess(true);
        settings.setSupportMultipleWindows(true);
        //设置缓存模式
//        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);//设置js可以直接打开窗口，如window.open()，默认为false
        settings.setSupportZoom(true);//是否可以缩放，默认true
//        settings.setBuiltInZoomControls(true);//是否显示缩放按钮，默认false
        settings.setUseWideViewPort(true);//设置此属性，可任意比例缩放。大视图模式
        settings.setLoadWithOverviewMode(true);//和setUseWideViewPort(true)一起解决网页自适应问题
        settings.setTextZoom(100); // 就可以禁止缩放，按照百分百显示。
        settings.setAppCacheEnabled(false);//是否使用缓存
        settings.setDomStorageEnabled(true);//DOM Storage
        settings.setAllowFileAccess(true); // 允许访问文件
        // displayWebview.getSettings().setUserAgentString("User-Agent:Android");//设置用户代理，一般不用
        settings.setPluginState(WebSettings.PluginState.ON);
        //为什么要加这句，http://blog.csdn.net/u013320868/article/details/52837671 访问这个就可以了
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            //设置允许加载混合内容
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        return settings;
    }

    protected void setWebViewChormeClient(WebView webView, ContentLoadingProgressBar progress) {


        webView.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onReceivedTitle(WebView view, String title1) {
            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (activityWeakReference.get() != null) {
                    if (newProgress == 100) {
                        progress.setVisibility(View.GONE);//加载完网页进度条消失
                        if (!getLocalClassName().contains("GoodsDetailsActivity")) {
                            dismissLoadingBar("");
                        }
                    } else {
                        if (!isShowloading) {
                            showLoadingBar("");
                            isShowloading = true;
                        }
                        progress.setVisibility(View.VISIBLE);//开始加载网页时显示进度条
                        progress.setProgress(newProgress);//设置进度值
                    }
                }
                super.onProgressChanged(view, newProgress);
            }

            // For 3.0+ Devices (Start)
            // onActivityResult attached before constructor
            protected void openFileChooser(ValueCallback uploadMsg, String acceptType) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                startActivityForResult(Intent.createChooser(i, "File Browser"), FILECHOOSER_RESULTCODE);
            }


            // For Lollipop 5.0+ Devices
            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
                if (uploadMessage != null) {
                    uploadMessage.onReceiveValue(null);
                    uploadMessage = null;
                }

                uploadMessage = filePathCallback;

                Intent intent = fileChooserParams.createIntent();
                try {
                    startActivityForResult(intent, REQUEST_SELECT_FILE);
                } catch (ActivityNotFoundException e) {
                    uploadMessage = null;
                    Toast.makeText(getBaseContext(), "Cannot Open File Chooser", Toast.LENGTH_LONG).show();
                    return false;
                }
                return true;
            }

            //For Android 4.1 only
            protected void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                mUploadMessage = uploadMsg;
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setType("image/*");
                startActivityForResult(Intent.createChooser(intent, "File Browser"), FILECHOOSER_RESULTCODE);
            }

            protected void openFileChooser(ValueCallback<Uri> uploadMsg) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
            }

        });
        webView.setWebViewClient(new WebViewClient() {


//            @Override
//            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
//               H5Hepler.alterSSL(mActivity,view,handler,error);
//            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
//                web_botice.loadUrl(url);//这样调用容易死循环  如果不需要对地址做特殊重定向处理 最好别重写此方法
                return super.shouldOverrideUrlLoading(view, request);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                d(format("--->>>>>>>>---onPageFinished"));
                if (activityWeakReference.get() != null) {
                    H5Activity.this.onPageFinished(url);
                    if (!getLocalClassName().contains("GoodsDetailsActivity")) {
                        dismissLoadingBar("");
                    }
                }
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                d(format("--->>>>>>>>---onReceivedError"));
                if (activityWeakReference.get() != null) {
                    dismissLoadingBar("");
                }
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                d(format("--->>>>>>>>---onPageStarted"));
                if (activityWeakReference.get() != null) {
                    loadUrl(url);
                }
            }

        });
    }

    protected void loadUrl(String url) {
        d("--->>>>>>>>---loadUrl:" + url);
    }

    protected void onPageFinished(String url) {

    }

    @Override
    public void getProductIdByUrlResult(ResultModel<ThirdContentModel> resultModel) {
        if (resultModel.isSuccess()) {
            ThirdContentModel model = resultModel.getData();
            if (model != null && model.getId() > 0) {
                GoodsDetailsActivity.startGoodsDetailsActivity(mActivity, model.getId());
            }
        }
    }

    @Override
    public void changeWishTypeResult(ResultModel resultModel, H5WishBean h5WishBean, boolean finalIsWish) {
        if (resultModel.isSuccess()) {
            ToastUtil.showToast(resultModel.getMsg());
            EventBus.getDefault().post(new UpdateWisnStateEvent(h5WishBean.getGoods_id(), finalIsWish));
            changeWishType(getWebView(), h5WishBean);
        }

    }

    @Override
    public void addGoodMallResult2(ResultModel resultModel) {

    }

    @Override
    public void addGoodMallResult(ResultModel<AddCartModel> resultModel, boolean isBuyNow) {

    }

    @Override
    public void searchProductBySnapResult(String s) {

    }

    @Override
    public void thirdTopupResult(ResponseBody responseBody) {

    }

    @Override
    public void onBackPressed() {
        onBack(getWebView());
//        super.onBackPressed();
    }

    protected void onBack(WebView webView) {
        if (webView.canGoBack()) {
            webView.goBack();
        } else {
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        WebView webView = getWebView();
        webView.removeAllViews();
        webView.destroy();
        ViewParent parent = webView.getParent();
        if (parent != null && parent instanceof ViewGroup) {
            ((ViewGroup) parent).removeView(webView);
        }
        webView = null;
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onUpdateWishEvent(UpdateWisnStateEvent event) {
        if (event != null) {
            changeWishType(getWebView(), "0", event.product_id, event.isWish);
//            String goods_url = h5GoodsDetailBean.getGoods_url();
//            if (h5GoodsDetailBean != null && !TextUtils.isEmpty(goods_url)) {
//                if (goods_url.contains(event.product_id)) {
//                }
//            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onLoginEvent(LoginEvent event) {
        //登录状态有改变
        if (event != null) {

            if (TextUtils.equals(event.loginState, CommonConstant.LOGIN_SUCCESS)) {
                d("--->>>>>>>>---登录成功");
            } else if (TextUtils.equals(event.loginState, CommonConstant.LOGOUT_SUCCESS)) {
                d("--->>>>>>>>---退出登录");
            }
        }


    }

    //当然调用系统相机或相册需要回到当前页面 需要把回传值处理一下
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            if (requestCode == REQUEST_SELECT_FILE) {
                if (uploadMessage == null)
                    return;
                uploadMessage.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
                uploadMessage = null;
            }
        } else if (requestCode == FILECHOOSER_RESULTCODE) {
            if (null == mUploadMessage)
                return;
            Uri result = data == null || resultCode != Activity.RESULT_OK ? null : data.getData();
            mUploadMessage.onReceiveValue(result);
            mUploadMessage = null;
        } else {
            Toast.makeText(getBaseContext(), "Failed to Upload Image", Toast.LENGTH_LONG).show();
        }
    }
}
